import LanguageUtils from '../../utils/LanguageUtils';
import React from 'react';
import {
  View,
  Text,
  TextInput,
  ScrollView,
  Keyboard,
  Alert,
} from 'react-native';

import Config from '../../config';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import ToastUtils from '../../common/ToastUtils';
import BasePage from '../common/BasePage';
import TImageUpLoadMultiComponent from '../../components/TImageUpLoadMultiComponent';

export default class CommonWritePage extends BasePage {
  constructor(props) {
    super(props);

    this._itemDatas = [];

    this._imageComponentDic = {};

    this.state.keyboardHeight = 0;
    this.state.itemHeightDic = {};

    this._scrollViewContentSize = 0;
    this._scrollViewHeight = SizeUtils.getWindowSize().height - Config.paddingTop;

    this._uploadImageCount = 0;

    this._updateActionName = null;
    this._updateAction = null;
    this._successText = "";
    this._failText = "";
  }

  _dealComponentWillUpdate(nextProps, nextStates) {
    super._dealComponentWillUpdate(nextProps, nextStates);

    if(nextStates.updateAction && nextStates.updateAction.name === this._updateActionName) {
      if(nextStates.updateAction.result === true) {
        Alert.alert('提示', this._successText ,[
            {text:'确定',onPress:()=>{this.goBack()}}
          ]);
      }
      else {
        Alert.alert('提示', this._failText + nextStates.updateAction.data,[
            {text:'确定',onPress:()=>{}}
          ]);
      }
      nextStates.showLoadingMask = false;
      nextStates.updateAction = null;
    }
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _dealLeavePage() {
    super._dealLeavePage();

    for(let key in this._imageComponentDic) {
      if(this._imageComponentDic[key]) {
        this._imageComponentDic[key].reset();  
      }
    }
    this._imageComponentDic = {};
  }

  _renderContent() {
    return (
      <ScrollView style={{paddingTop:Config.paddingTop}}
        ref={(ref) => {this._scrollView = ref}} onContentSizeChange={this._onScrollViewContentSizeChange.bind(this)}>
        {
          this._itemDatas.map(
            (itemData, index) => {
              let itemHeight = itemData.height;
              if(this.state.itemHeightDic[itemData.stateKey]) {
                itemHeight = Math.max(this.state.itemHeightDic[itemData.stateKey], itemData.height);
              }
              return (
                <View key={index} style={{width:SizeUtils.getWindowSize().width,
                      paddingLeft:SizeUtils.translateDesignWidthToCode(40),
                      paddingRight:SizeUtils.translateDesignWidthToCode(40),
                      height:itemHeight,
                      borderColor:"#eeeeee",
                      borderBottomWidth:index === this._itemDatas.length - 1 ? 0 : SizeUtils.translateDesignNumToCode(3),
                      flexDirection:"row", alignItems:itemData.alignItems,
                    }}>
                  {this._renderItem(itemData)}
                </View>
              );
            }
          )
        }
        <View style={{width:SizeUtils.getWindowSize().width, height:this.state.keyboardHeight,}}>
        </View>
      </ScrollView>
    )
  }

  _renderItem(itemData) {
    if(itemData.type === "text") {
      return this._renderTextItem(itemData);
    }
    else if(itemData.type === "uploadImage") {
      return this._renderImageUploadItem(itemData);
    }
  }

  _renderTextItem(itemData) {
    let itemHeight = itemData.height;
    if(this.state.itemHeightDic[itemData.stateKey]) {
      itemHeight = Math.max(this.state.itemHeightDic[itemData.stateKey], itemData.height);
    }
    return (
      <View style={{height:itemHeight - SizeUtils.translateDesignHeightToCode(60)}}>
        <TextInput
          style={{padding:0,
            width:SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80),
            height:itemHeight - SizeUtils.translateDesignHeightToCode(40),
            fontSize:SizeUtils.translateFontSizeToCode(itemData.fontSize)}}
          onChangeText = {
            (value) => {
              var state = {};
              state[itemData.stateKey] = value;
              this.setState(state);
            }
          }
          placeholder = {itemData.placeholder}
          underlineColorAndroid="transparent"
          multiline = {itemData.multiline}
          value = {this.state[itemData.stateKey] ? this.state[itemData.stateKey] : ""}
          onContentSizeChange={(event) => this._onContentSizeChange(event, itemData)}
        />
      </View>
    )
  }

  _renderImageUploadItem(itemData) {
    let width = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80);
    return(
      <TImageUpLoadMultiComponent
        ref={(ref) => this._imageComponentDic[itemData.stateKey] = ref}
        style={{width:width, height:itemData.height}}
        resizeMode={"cover"}
        containerStyle={{width:width,
          height:itemData.height, paddingTop:SizeUtils.translateDesignHeightToCode(20)}}
        imageStyle={{width:itemData.imageWidth, height:itemData.imageHeight}} maxCount = {itemData.imageCount}
        />
    )
  }

  _onScrollViewContentSizeChange(contentWidth, contentHeight) {
    this._scrollViewContentSize = contentHeight;
  }

  _onContentSizeChange(event, itemData) {
    // console.log(event.nativeEvent);
    let itemHeightDic = this.state.itemHeightDic;
    itemHeightDic[itemData.stateKey] = event.nativeEvent.contentSize.height + SizeUtils.translateDesignHeightToCode(80);
    this.setState({itemHeightDic: itemHeightDic}, ()=> {
      this._scrollToEnd();
    });
  }

  _keyboardDidShow(e){
    if(e.endCoordinates){
         this.setState({
          keyboardHeight:e.endCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }else if(e.startCoordinates){
        this.setState({
          keyboardHeight:e.startCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }
  }

  _keyboardDidHide(e){
      this.setState({
          keyboardHeight:0
      }, ()=> {
        setTimeout(()=>{
          this._scrollView.scrollTo({y:0});
        }, 500);
      })
  }

  _scrollToEnd() {
    if(this._scrollViewContentSize > this._scrollViewHeight) {
      setTimeout(()=>{
        this._scrollView.scrollToEnd();
      }, 100);
    }
  }

  _onPressNavigationBarRightBtn() {
    if(this._checkDataleagl()) {
      this._uploadData();
    }
  }

  _checkDataleagl() {
    for (var i = 0; i < this._itemDatas.length; i++) {
      if(this._itemDatas[i].isNeed) {
        if(this._itemDatas[i].type === "uploadImage") {
          if(this._imageComponentDic[this._itemDatas[i].stateKey].checkIsEmpty()) {
            ToastUtils.show(this._itemDatas[i].name + '不能为空');
            return false;
          }
        }
        else {
          if(!this.state[this._itemDatas[i].stateKey]) {
            ToastUtils.show(this._itemDatas[i].name + '不能为空');
            return false;
          }
        }
      }
    }
    return true;
  }

  _uploadData() {
    this.setState({
      showLoadingMask:true,
    });
    this._uploadImages();
  }

  _uploadImages() {
    this._uploadImageCount = 0;
    for(let key in this._imageComponentDic) {
      this._uploadImageCount++;
      this._imageComponentDic[key].doUpload((image_urls) => this._onUploadImageCallback(image_urls, key));
    }
  }

  _onUploadImageCallback(image_urls, key) {
    var state = {};
    state[key] = image_urls;
    this.setState(state);

    this._uploadImageCount--;
    if(this._uploadImageCount === 0) {
      this._uploadImagesFinish();
    }
  }

  _uploadImagesFinish() {
    this._sendAction();
  }

  _sendAction() {
    var sendData = {};
    for (var i = 0; i < this._itemDatas.length; i++) {
      sendData[this._itemDatas[i].stateKey] = this.state[this._itemDatas[i].stateKey];
    }
    new this._updateAction().call(this, sendData);
  }
}
